# -*- codeing = utf-8 -*-
# !/usr/bin/env python
# @coding  : utf-8
# @File    : t3.py
# @Time    : 2022/5/27 20:15
# @Author  : xdd
# @Software: PyCharm
# @desc :$
k = 3
i = 1

min1 = data.min(axis=0)
max1 = data.max(axis=0)

# 在数据最大最小值中随机生成k个初始聚类中心，保存为t
centre = np.empty((k, 2))
for i in range(k):
    centre[i][0] = random.randint(min1[0], max1[0])  # 平时成绩
    centre[i][1] = random.randint(min1[1], max1[1])  # 期末成绩

while i < 500:

    # 计算欧氏距离
    def euclidean_distance(List, t):
        return math.sqrt(((List[0] - t[0]) ** 2 + (List[1] - t[1]) ** 2))


    # 每个点到每个中心点的距离矩阵
    dis = np.empty((len(data), k))
    for i in range(len(data)):
        for j in range(k):
            dis[i][j] = euclidean_distance(data[i], centre[j])

    # 初始化分类矩阵
    classify = []
    for i in range(k):
        classify.append([])

    # 比较距离并分类
    for i in range(len(data)):
        List = dis[i].tolist()
        index = List.index(dis[i].min())
        classify[index].append(i)

    # 构造新的中心点
    new_centre = np.empty((k, 2))
    for i in range(len(classify)):
        new_centre[i][0] = np.sum(data[classify[i]][0]) / len(classify[i])
        new_centre[i][1] = np.sum(data[classify[i]][1]) / len(classify[i])

    # 比较新的中心点和旧的中心点是否一样
    if (new_centre == centre).all():
        break
    else:
        centre = new_centre
        i = i + 1

# print('迭代次数为：',i)
print('聚类中心为：', new_centre)
print('分类情况为：', classify)